import React, { Component } from 'react'

import { inject, observer } from 'mobx-react/native'
import { Mutation, graphql } from 'react-apollo'
import gql from 'graphql-tag'

import moment from 'moment'
import { Carousel, Modal, Toast, WhiteSpace } from 'antd-mobile'
import {
  Button,
  Dimensions,
  Image,
  ScrollView,
  StyleSheet,
  View,
} from 'react-native'

import { IconButton, Entity, WhiteButton } from '../components'
import client from '../client'
import store from '../store'

const QUERY_ORDER = gql`
  query($id: ID!) {
    Order(id: $id) {
      id
      items {
        item {
          id
          title
          price
        }
        amount
      }
      state
      createdAt
      updatedAt
    }
  }
`

const UPDATE_ORDER = gql`
  mutation($id: ID!, $state: OrderState!) {
    updateOrder(id: $id, state: $state) {
      id
    }
  }
`

@graphql(QUERY_ORDER, {
  options: ({ navigation }) => ({
    variables: { id: navigation.getParam('id') },
    fetchPolicy: 'network-only',
  }),
})
export class OrderScreen extends Component {
  get data() {
    const key = 'Order'
    const loaded = this.props.data && !this.props.data.loading
    const data = loaded ? this.props.data[key] : {}
    return data
  }

  render = () => (
    <ScrollView style={styles.container}>
      {/* <Carousel infinite>
        {this.data.images.map(uri => (
          <Image
            key={uri}
            style={{ width: Dimensions.get('window').width, height: 200 }}
            source={{ uri }}
          />
        ))}
      </Carousel> */}
      <Entity
        data={this.data}
        loading={this.props.data.loading}
        schema={[
          {
            key: 'createdAt',
            label: 'Create Time',
            render: time => moment(time).calendar(),
          },
          {},
          ...(this.data.items || []).map(({ item, amount }, i) => ({
            key: `items-${i}`,
            label: i === 0 ? 'Items' : ' ',
            render: () => `${item.title} (${amount})`,
          })),
          {},
          {
            key: 'price',
            label: 'Price',
            render: () => (totalPrice(this.data.items) / 100).toFixed(2),
          },
          {},
          { key: 'state', label: 'State' },
          {},
          {
            key: 'updatedAt',
            label: 'Update Time',
            render: time => moment(time).calendar(),
          },
        ]}
      />
      <WhiteSpace />
      <Mutation mutation={UPDATE_ORDER}>
        {mutate => (
          <WhiteButton
            title="Mark Finished"
            onPress={async () => {
              await mutate({
                variables: {
                  id: this.props.navigation.getParam('id'),
                  state: 'FINISHED',
                },
              })
              Toast.success('Success', 1, undefined, false)
            }}
          />
        )}
      </Mutation>
    </ScrollView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
})

const totalPrice = items =>
  items.map(t => t.item.price * t.amount).reduce((x, y) => x + y, 0)
